package com.example.ui.leftmenu;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;



import com.baidu.android.common.util.Util;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.example.entity.ShareEntity;
import com.example.huashangapp.BaseView;
import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.net.Communication;
import com.example.net.NetContact;
import com.example.service.MainService;
import com.example.ui.contact.AddFriendActivity;
import com.example.ui.contact.BladeView;
import com.example.ui.contact.MsgState;
import com.example.ui.contact.BladeView.OnItemClickListener;
import com.example.ui.contact.PersonHomeActivity;
import com.example.ui.contact.adapter.ContactsListViewAdapter;
import com.example.ui.contact.adapter.NearListViewAdapter;
import com.example.ui.contact.bean.Contact;
import com.example.ui.contact.bean.HomeItem;
import com.example.ui.contact.bean.ImageItem;
import com.example.ui.contact.bean.PicItem;
import com.example.ui.contact.bean.ShareItem;
import com.example.ui.contact.bean.User;
import com.example.ui.contact.chat.ChatActivity;
import com.example.ui.contact.chat.L;
import com.example.ui.contact.chat.PushMessageReceiver.EventHandler;
import com.google.gson.JsonObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * 学友列表view
 * @author Leone
 *
 */
public class Item08View extends BaseView implements EventHandler{
	
	//private static String requestURL="http://192.168.1.108:8080/huashangService/";  //192.168.137.1
	/**
	 * 分组的布局
	 */
	//private LinearLayout titleLayout;

	/**
	 * 分组上显示的字母
	 */
	private TextView title;

	/**
	 * 联系人ListView
	 */
	private ListView contactsListView;



	/**
	 * 用于进行字母表分组
	 */
//	private AlphabetIndexer indexer;

	/**
	 * 存储所有手机中的联系人
	 */
	public static  List<Contact> contacts = new ArrayList<Contact>();
	
	public static int contacts_length;
	/**
	 * 存储搜索框中的联系人
	 */
	public List<User> searchList = new ArrayList<User>();
	
	/**
	 * 存储当前显示的联系人
	 */
	public List<User> nowList = new ArrayList<User>();	
	
	/**
	 * 储存所有的学友列表信息
	 */
	public static  List<User> study_list = new ArrayList<User>();
	/**
	 * 储存所有附近的人列表信息
	 */
	public static  List<User> near_list = new ArrayList<User>();
	
	/**
	 * 联系人列表适配器
	 */
	public static ContactsListViewAdapter adapter;
	
	/**
	 * 定义字母表的排序规则
	 */
	private String alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	/**
	 * 上次第一个可见元素，用于滚动时记录标识。
	 */
	//private int lastFirstVisibleItem = -1;

	private TabHost tabHost;
	private View userTab,articeTab;  	
	private View[] tabs = new View[]{userTab,articeTab};  
	private String[] tabBtnName = new String[]{"我的学友","附近的人"};  	//,"私信消息"
	private int[] tabIds = new int[]{R.id.tab1,R.id.tab2}; 
	

	private ListView near_people_list;
	public static int near_cur_index;
	//private int[] near_people_imgArr = {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,
	//		R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,
	//		R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
	
	public static Context context;  //Context
	private Button titleLeftBtn, titleRightBtn;
	private TextView titleText;
	private EditText editText;
	private LinearLayout pb;
	private String url = Communication.BASEURL+"/demo";
	/*
	 * 返回的添加学友界面的数据
	 */
	public static String[] invite_num;
	public static String phone;

	public int fd_length;
	public static int ie_length;
	public static String[] fd_num;
	public static String[] fd_name;
	public static String[] fd_id;
	
	/**
	 * 附近的人相关变量
	 */
	public static int near_length;
	public static String [] name;//={"孙中山","蒋介石","毛泽东","周恩来","江泽民","朱镕基","胡锦涛","温家宝","习近平","李克强"}
	public static String [] distance;
	
	/**
	 * 定位相关
	 */
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();	
	MyLocationOverlay myLocationOverlay = null;
	int index =0;
	LocationData locData = null;
	Button testUpdateButton = null;	
	public static  double latitude = 0.1;
	public static  double longitude = 0.2;
	
	HSApplication application;

	private HSApplication hsApplication;
    public void initLBS(){
    	HSApplication app = HSApplication.getInstance();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(context);
            app.mBMapManager.init(HSApplication.mapKey,new HSApplication.MyGeneralListener());
        }
        
        locData = new LocationData();
        mLocClient = new LocationClient(context);
        mLocClient.registerLocationListener(myListener);
        
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);//打开gps
        option.setCoorType("bd09ll");     //设置坐标类型
        option.setScanSpan(10000);
        mLocClient.setLocOption(option);
        mLocClient.start();

    }
    public void testUpdateClick(){
        mLocClient.requestLocation();
    }	
	/**
     * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return ;
            
            locData.latitude = location.getLatitude();
            locData.longitude = location.getLongitude();
            locData.accuracy = location.getRadius();
            locData.direction = location.getDerect();
            
            latitude = locData.latitude;
            longitude = locData.longitude;
            

        }
        
        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null){
                return ;
            }
        }
    }	

	public Item08View(Context context, HSApplication hsApplication) {
		this.context = context;
		this. hsApplication=hsApplication;
	}
    private static AsyncHttpClient client = new AsyncHttpClient();
   // private static final Pattern PAT_URL = Pattern.compile("\\:(\\S+?)\\|");
    public static String[] send_num;
    //private boolean isRun = false;
	public void SendNum(String url){
		pb.setVisibility(View.VISIBLE);
		final int length = contacts.size();
        send_num = new String[length];
    	RequestParams params = new RequestParams();
    	for(int i=0;i<length;i++){
    		//data
    		String  num = contacts.get(i).getNum().trim()+"|";
    		if(i==0){
    			phone = num;
    		}else{
    			phone +=num;
    		} 
    		
    	}
    	L.Debug("SendNum 上传", phone);
		params.put("contacts",phone );// "18610798479|15618241817|124555"
		client.post(
				NetContact.SEND_PHONE_URL,
				params, new JsonHttpResponseHandler() {
	
					
					@Override
					public void onSuccess(JSONObject response) {
						L.Debug("SendNum response", response.toString());

							JSONArray jsonArray;
							try {
								jsonArray = response.getJSONArray("response");
								L.Debug("SendNum 返回", jsonArray.toString());
								ie_length = jsonArray.length();
								invite_num = new String[ie_length];
								for(int i=0;i<ie_length;i++){
									invite_num[i]=jsonArray.getString(i);
									L.Debug("SendNum invite_num["+i+"]", invite_num[i]);
								}
								pb.setVisibility(View.GONE);
			                    Intent intent = new Intent(context,AddFriendActivity.class);
			                    intent.putExtra("invite_num", invite_num);
			                    context.startActivity(intent);  
							} catch (JSONException e) {
								e.printStackTrace();
								L.Debug("SendNum JSONException", e.getMessage());
							}							
						}
													

				});

	}
	
	public void getUserInfo() {
		
		RequestParams params = new RequestParams();
		User user = new User();

		params.put("userId", user.getUserId());
		params.put("nick", user.getNick());
		params.put("headImg", ""+user.getHeadIcon());
		params.put("telNum", user.getTelNum());

		
	}
	
	public void LoadFriends(){
		pb.setVisibility(View.VISIBLE);
		String uid = HSApplication.sp.getString("userid","");  
    	RequestParams params = new RequestParams();
    	params.put("uid", uid);//"123"  //上传自己的id给服务器
    	client.post(NetContact.LOAD_FD_URL, params,new JsonHttpResponseHandler(){


    		@Override
    		public void onSuccess(JSONObject response) {
    			
    			super.onSuccess(response);
    			L.Debug("onSuccess2", "run");
    			L.Debug("好友列表 返回", response.toString());

				try {
							JSONArray jsonArray = response
									.getJSONArray("response");
							fd_length = jsonArray.length();
							fd_num = new String[fd_length];
							fd_name = new String[fd_length];
							fd_id = new String[fd_length];
							study_list.clear();
							for (int i = 0; i < fd_length; i++) {
								fd_num[i] = jsonArray.getJSONObject(i)
										.getString("mobile");
								fd_name[i] = jsonArray.getJSONObject(i)
										.getString("username");
								fd_id[i] = jsonArray.getJSONObject(i)
										.getString("id");
								
								User user = new User();								
								user.setTelNum(fd_num[i]);
								user.setNick(fd_name[i]);
								user.setId(fd_id[i]);
//								for(int k =0; k<study_list.size();k++){
//									if(fd_id[i].equals(object))
//								}
								study_list.add(user);
								L.Debug("fd_num[" + i + "]", fd_num[i]);
							}
							
							adapter.notifyDataSetChanged();
							pb.setVisibility(View.GONE);
						} catch (JSONException e) {
							
					pb.setVisibility(View.GONE);
					L.showShort(context, "网络异常，获取好友列表失败,请重新登录");
					e.printStackTrace();
				}
				
				}    			

    		
    		@Override
    		public void onFailure(Throwable error) {
                 L.Debug("initData error", error.toString()) ;   			
    		}

    	});		
	}
	public void init(){
      	//获取电话号码
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		Cursor cursor = this.context.getContentResolver().query(uri,
					new String[]{ContactsContract.Contacts.DISPLAY_NAME,
					"sort_key",ContactsContract.Contacts._ID}, null, null, "sort_key");			
			
			if (cursor.moveToFirst()) {
				do {
					String name = cursor.getString(cursor.getColumnIndex("display_name"));

					String sortKey = getSortKey(cursor.getString(cursor.getColumnIndex("sort_key")));
					

					//查询电话号码数据库
		            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
		            Cursor phone = this.context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
		            		null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);

		            String PhoneNumber ="00000";
		            //取得电话号码
		            while(phone.moveToNext())
		            {
		                 PhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
		            }
		            Contact contact = new Contact();
					contact.setNum(PhoneNumber);
					contact.setName(name);
					contact.setSortKey(sortKey);
					contacts.add(contact);

				} while (cursor.moveToNext());
			}
	    L.Debug("contacts size", ""+contacts.size());
	    contacts_length = contacts.size();
		
		initView(); 
		//获取学友列表数据
		LoadFriends();
		
 	
			
			
	    application = HSApplication.getInstance();
			
		//UserDB userDB = application.getUserDB();
		//study_list  = userDB.getUser();
        

		//indexer = new AlphabetIndexer(cursor, -1, alphabet);
		//adapter.setIndexer(indexer);	
		
		
		//setupContactsListView();//显示学友列表

	}
	/**
	 * Leone add
	 */
	private BladeView mLetter;
	public void initView(){

		view = LayoutInflater.from(context).inflate(R.layout.chat_item_list, null);
		pb=(LinearLayout)view.findViewById(R.id.progressbar);
		titleLeftBtn = (Button)view.findViewById(R.id.layout_title_left_btn);
		titleRightBtn= (Button) view.findViewById(R.id.layout_title_right_btn);
		titleText=(TextView)view.findViewById(R.id.layout_title_middle_text);		
		editText = (EditText)view.findViewById(R.id.editText);
		
		//chatGroup=(RadioGroup)view.findViewById(R.id.chat_tab_radio);	
		


		//titleLayout = (LinearLayout)view.findViewById(R.id.title_layout);
		title = (TextView)view.findViewById(R.id.title);
		contactsListView = (ListView)view.findViewById(R.id.contacts_list_view);

		titleLeftBtn.setText("菜单");
		titleText.setText("学友");
		titleRightBtn.setText("加学友");

		//		adapter = new ContactsListViewAdapter(this.context,study_list);
		//		contactsListView.setAdapter(adapter);	
		//我的学友列表
		init_Study_List();
		
		titleRightBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SendNum(url);
              	

			}
		});

		titleLeftBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				myMoveView.showHideLeftMenu();
				if(MainService.isLeftMenu==true){
			//					if(tabHost.getCurrentTab()==0){
			//						contactsListView.setEnabled(false);
			//					}else if(tabHost.getCurrentTab()==1){
			//						near_people_list.setEnabled(false);
			//					}
					
					editText.setEnabled(false);
				}else{
			//					if(tabHost.getCurrentTab()==0){
			//						contactsListView.setEnabled(true);
			//					}else if(tabHost.getCurrentTab()==1){
			//						near_people_list.setEnabled(true);
			//					}
					
					editText.setEnabled(true);
				}
			}
		});
		
		
		
		mLetter = (BladeView) view.findViewById(R.id.friends_myletterlistview);
		mLetter.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(String s) {
				mLetter.setIndex(s);
				int sectionIndex = mLetter.getIndex();
				title.setText(String.valueOf(alphabet.charAt(sectionIndex)));
				if (String.valueOf(alphabet.charAt(sectionIndex)) != null) {
					//contactsListView.setSelection(indexer.getPositionForSection(sectionIndex));
					
				}
				
			}
		});
		
		
		editText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
				L.Debug("editText run", "");
				if(s.length()!=0){
					getSearchUser(s.toString());
					adapter.list= searchList;
					
				}else{					
					adapter.list = nowList;
				
				}
				adapter.notifyDataSetChanged();
				contactsListView.invalidate();
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
		
		tabHost=(TabHost)view.findViewById(R.id.item08_tabhost);
		tabHost.setup();
	
		for(int i=0;i<tabs.length;i++){
            tabs[i] = (View) LayoutInflater.from(context).inflate(R.layout.item07_tabwidget, null);
            TextView text = (TextView) tabs[i].findViewById(R.id.tabwidget_text);
            text.setText(tabBtnName[i]);   
            tabHost.addTab(tabHost.newTabSpec(tabBtnName[i]).setIndicator(tabs[i]).setContent(tabIds[i])); 
        } 
		tabHost.setCurrentTab(0);

		tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			
			@Override
			public void onTabChanged(String tabId) {
		        if(tabId.equals(tabBtnName[0])){  
		        	titleText.setText("我的学友");
		        	//初始化学友列表
		        	MsgState.state = MsgState.FD_LIST_MSG_STATE;
		        	init_Study_List();
		        }  
		        if(tabId.equals(tabBtnName[1])){ 
		        	
		        	titleText.setText("附近的人");
		        	
		    		new AlertDialog.Builder(context).setTitle("提示")
		    		.setMessage("需要提交自己的位置")
		    		.setNegativeButton("取消",  new DialogInterface.OnClickListener() {

		    			@Override
		    			public void onClick(DialogInterface dialog, int which) {
		    				tabHost.setCurrentTab(0);
		    			}
		    			
		    		})
		    		.setPositiveButton("确定", new DialogInterface.OnClickListener() {

		    			@Override
		    			public void onClick(DialogInterface dialog, int which) {
		    				initLBS();
		    				LoadNear();
		    			}
		    			
		    		}).show();
		        }  

				
			}
		});
		

		
//		chatGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//			
//
//			@Override
//			public void onCheckedChanged(RadioGroup arg0, int rid) {
//				switch (rid) {
//				case R.id.radio_button0:
//					editText.setText("");
//					tabHost.setCurrentTab(0);
//					titleText.setText("我的学友");
//					titleRightBtn.setVisibility(View.VISIBLE);
//					break;
//				case R.id.radio_button1:
//					tabHost.setCurrentTab(1);
//					titleText.setText("附近的人");
//					titleRightBtn.setVisibility(View.INVISIBLE);
//		    		new AlertDialog.Builder(context).setTitle("提示")
//		    		.setMessage("需要提交自己的位置")
//		    		.setNegativeButton("取消",  new DialogInterface.OnClickListener() {
//
//		    			@Override
//		    			public void onClick(DialogInterface dialog, int which) {
//		    				
//		    				tabHost.setCurrentTab(0);
//		    			}
//		    			
//		    		})
//		    		.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//		    			
//		    			@Override
//		    			public void onClick(DialogInterface dialog, int which) {
//		    				tabHost.setCurrentTab(1);
//		    				testUpdateClick();
//		    				L.Debug("latitude",""+latitude);
//		    				L.Debug("longitude",""+longitude);
//		    				
//		    			   	RequestParams params = new RequestParams();
//		    			   	params.put("latitude", ""+latitude);
//		    				params.put("longitude", ""+longitude);
//		    		    	client.post(url, params,new JsonHttpResponseHandler(){
//		    		    		@Override
//		    		    		public void onSuccess(int statusCode, JSONObject response) {
//		    		    			 data = response.toString();
//		    		    		}
//		    		    		@Override
//		    		    		public void onFailure(Throwable error) {
//		    		    		}
//		    		    	});
//		    		    	
//		    				//附近的人列表
//		    				near_people_list = (ListView)view.findViewById(R.id.item_nearpeople_listview);//item_nearpeople_listview
//		    				near_people_list.setAdapter(new NearListViewAdapter(context));
//		    				near_people_list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
//
//		    					@Override
//		    					public void onItemClick(AdapterView<?> parent, View v, int position,
//		    							long id) {
//		    						Intent chatIntent = new Intent(context,ChatActivity.class);
//		    						context.startActivity(chatIntent);
//		    					}
//
//		    				});
//		    			}
//		    			
//		    		}).show();					
//					break;
//
//				default:
//						break;
//				}
//			}
//		});		

	}
	
	/**
	 * 上传附近的人数据信息
	 */
	public void LoadNear(){
		pb.setVisibility(View.VISIBLE);
		testUpdateClick();
        mLocClient.stop();
		L.Debug("latitude", ""+latitude);
		L.Debug("longitude", ""+longitude);
		
    	RequestParams params = new RequestParams();

		params.put("uid", "123");
		params.put("lng", String.valueOf(latitude));
		params.put("lat", String.valueOf(longitude));
		client.post(
				NetContact.LOAD_NEAR_URL,
				params, new JsonHttpResponseHandler() {
	
					
					@Override
					public void onSuccess(JSONObject response) {
						L.Debug("附近的人 response1", response.toString());
						JSONArray jsonArray;
						try {
							jsonArray = response.getJSONArray("response");
							near_length = jsonArray.length();
							L.Debug("near_length", ""+near_length);
							name = new String[near_length];
							distance = new String[near_length];
							L.Debug("附近的人 response2", jsonArray.toString());
							for(int i=0;i<near_length;i++){
								L.Debug("name["+i+"]", name[i]);
								name[i]= jsonArray.getJSONObject(i).getString("username");
								distance[i]= jsonArray.getJSONObject(i).getString("distance");
								
								String id = jsonArray.getJSONObject(i).getString("id");
								String dis= jsonArray.getJSONObject(i).getString("distance");
								String username = jsonArray.getJSONObject(i).getString("username");
								User user = new User();	
								
								user.setNick(username);
								user.setId(id);
								user.setDistatce(dis);
								near_list.add(user);
							}
							pb.setVisibility(View.GONE);
		    				//附近的人列表
		    				near_people_list = (ListView)view.findViewById(R.id.item_nearpeople_listview);
		    				NearListViewAdapter adapter = new NearListViewAdapter(context,near_list);
		    				near_people_list.setAdapter(adapter);
		    				near_people_list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

		    					@Override
		    					public void onItemClick(AdapterView<?> parent, View v, int position,
		    							long id) {
		    						isNear = true;
		    						near_cur_index = position;
		    						String uid = near_list.get(near_cur_index).getId();
		    						NetLoadHome(false,uid);

		    					
		    					}

		    				});		    									

						} catch (JSONException e) {
							e.printStackTrace();
							L.Debug("附近的人  JSONException", e.getMessage());
						}
								
					}

				});	
	}

	

	/**
	 * 获取sort key的首个字符，如果是英文字母就直接返回，否则返回#。
	 * 
	 * @param sortKeyString
	 *            数据库中读取出的sort key
	 * @return 英文字母或者#
	 */
	private String getSortKey(String sortKeyString) {
		String key = sortKeyString.substring(0, 1).toUpperCase();
		if (key.matches("[A-Z]")) {
			return key;
		}
		return "#";
	}
	

	

	

	private void getSearchUser(String condition ) {
		searchList.clear();
		if (condition == null || condition.equals(""))
			return ;
       

		//while(contacts.getCur()>contacts.size())
		//String[] projection= {Phone.DISPLAY_NAME, Phone.NUMBER, Phone.PHOTO_ID, "sort_key"};
		//String selection = Phone.NUMBER + " like '%" + condition + "%' or " 
		//		 		 + Phone.DISPLAY_NAME + " like '%" + condition + "%' or "
		//		 		 + "sort_key" + " like '%" + getPYSearchRegExp(condition, "%") + "%'";
		//Cursor cur = context.getContentResolver().query(Phone.CONTENT_URI, projection, selection, null, Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
		//cur.moveToFirst();

	}
	

	@Override
	public void onMessage(String message) {
		
	}
	@Override
	public void onBind(String method, int errorCode, String content) {
		
	}
	@Override
	public void onNotify(String title, String content) {
		
	}
	@Override
	public void onNetChange(boolean isNetConnected) {
		
	}	
	
	public void Update_Study_List(){//String message
		//		String MeContent;
		//		try {
		//			MeContent = new JSONObject(message.toString()).getString("friendmsg");
		//			JSONObject json = new JSONObject(MeContent);
		//			JSONObject friend_json = json.getJSONObject("friend");
		//	
		//			String id = friend_json.getString("id");
		//			String mobile = friend_json.getString("mobile");
		//            String nick = friend_json.getString("username");
		//            L.Debug(" Add_Study_List id", id);
		//            L.Debug(" Add_Study_List mobile", mobile);
		//            L.Debug(" Add_Study_List username", nick);
		//			User user = new User();			
		//			user.setTelNum(mobile);
		//			user.setNick(nick);
		//			user.setId(id);
		//			Item08View.study_list.add(user);
		//			
		//			
		//		} catch (JSONException e) {
		//			L.Debug("Add_Study_List JSONException error", "");
		//			e.printStackTrace();
		//		}
		adapter.notifyDataSetChanged();


	}
	
	private static int fd_cur_index;
	public void init_Study_List(){
		//我的学友列表
		adapter = new ContactsListViewAdapter(this.context,study_list);
		contactsListView.setAdapter(adapter);	
		adapter.notifyDataSetChanged();
		contactsListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {


			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				isFd = true;
				fd_cur_index = position;
				String uid = study_list.get(position).getId();
				NetLoadHome(false,uid);
				//Intent intent = new Intent(context,PersonHomeActivity.class);
				//context.startActivity(intent);				
			}
		});

	}
	/**
	 * 个人主页面http请求
	 */
	public static  List<HomeItem> home_list = new ArrayList<HomeItem>();
	public static  List<ShareItem> share_list = new ArrayList<ShareItem>();
	public static  List<PicItem> pic_list = new ArrayList<PicItem>();
	public static  List<ImageItem> image_list = new ArrayList<ImageItem>();
	public static boolean isFd = false;
	public static boolean isNear = false; 
	public static void NetLoadHome(boolean isNum,String uid){
    	RequestParams params = new RequestParams();
    	params.put("uid", "5214");//5214  //上传自己的id给服务器
		//    	if(isNum){
		//    		params.put("count", "3");
		//    	}
    	client.post(NetContact.LOAD_HOME_URL, params,new AsyncHttpResponseHandler(){ 

    		@Override
    		public void onSuccess(String content) {
    			String str = content.toString();
    			L.Debug("个人主页面str", str);
    			image_list.clear();
    			pic_list.clear();
    			share_list.clear();
    			home_list.clear();
    			try {
					JSONObject home_data = new JSONObject(content).getJSONObject("home");
					JSONArray  share_json = home_data.getJSONArray("share");
					
					//个人主页String解析
					HomeItem homeitem = new HomeItem();
					String userPic = home_data.getString("userPic");
					String requirement = home_data.getString("requirement");
					String supply = home_data.getString("supply");
					String signature = home_data.getString("signature");
					homeitem.setUserPic(userPic);
					homeitem.setRequirement(requirement);
					homeitem.setSupply(supply);
					homeitem.setSignature(signature);
					
					//分享String解析
	    			for(int i= 0;i<share_json.length();i++){
	    				JSONObject data = share_json.getJSONObject(i);	
	    				L.Debug("LOAD_HOME_URL data", data.toString());
	    				ShareItem item= new ShareItem();
	    				
	    				if(data.optString("id")!=null){
		    				String id = data.getString("id");
		    				item.setUid(id);	    					
	    				}
	    				if(data.optString("typeId")!=null){
		    				String typeid = data.getString("typeId");
		    				item.setTypeId(typeid);					
	    				}
	    				if(data.optString("nickname")!=null){
		    				String nickname = data.getString("nickname");
		    				L.Debug("LOAD_HOME_URL nickname", nickname);
		    				item.setNickname(nickname);    					
	    				}
	    				if(data.optString("communityid")!=null){
		    				String communityid = data.getString("communityid");
		    				item.setCommunityid(communityid);    					
	    				}
	    				if(data.optString("txt")!=null){
		    				String txt = data.getString("txt");
		    				item.setTxt(txt);    					
	    				}
	    				if(data.optString("dateline")!=null){
		    				String dateline = data.getString("dateline");
		    				item.setDateline(dateline);    					
	    				}	    				
	    				if(data.optString("like")!=null){
		    				String like = data.getString("like");
		    				item.setLike(like);   					
	    				}
	    				if(data.optString("forward")!=null){
		    				String forward = data.getString("forward");
		    				item.setForward(forward);					
	    				}
	    				if(data.optString("reply")!=null){
		    				String reply = data.getString("reply");
		    				item.setReply(reply);				
	    				}
	    				if(data.optString("location")!=null){
		    				String location = data.getString("location");
		    				item.setLocation(location);				
	    				}

	    				if(data.optString("location")!=null){
		    				String location = data.getString("location");
		    				item.setLocation(location);				
	    				}
	    				JSONArray pic_data = data.getJSONArray("picList");
	    				for(int k =0;k<pic_data.length();k++){
	    					String id = pic_data.getJSONObject(k).getString("id");
	    					String timeline = pic_data.getJSONObject(k).getString("timeline");
	    					String pic = pic_data.getJSONObject(k).getString("pic");
	    					String thumb = pic_data.getJSONObject(k).getString("thumb");
	    					PicItem picitem = new PicItem();
	    					picitem.setId(id);
	    					picitem.setTimeline(timeline);
	    					picitem.setPic(pic);
	    					picitem.setThumb(thumb);
	    					
	    					item.getPicList().add(picitem);//照片的信息添加到分享容器中
	    					pic_list =  item.getPicList();
	    				}
	    				
	    				homeitem.getShareList().add(item);//分享的信息添加到主页容器中
	    				share_list.add(item);
	    			}
	    			//照片墙String解析
	    			JSONArray pic_json = home_data.getJSONArray("imageList");
	    			for(int j=0;j<pic_json.length();j++){
	    				
	    				ImageItem imageitem = new ImageItem();
	    				homeitem.getImageList().add(imageitem);//照片墙的信息添加到主页容器中
	    				
	    			}
	    			//share_list = homeitem.getShareList();
	    			image_list =  homeitem.getImageList();
	    			home_list.add(homeitem);
	    			
					Intent chatIntent = new Intent(context,PersonHomeActivity.class);
					//study_list.get(fd_cur_index).getNick();
					if(isFd){
						isFd = false;
						chatIntent.putExtra("mName",study_list.get(fd_cur_index).getNick() );
						chatIntent.putExtra("mId",study_list.get(fd_cur_index).getId());
					}
					if(isNear){
						isNear = false;
						chatIntent.putExtra("mName",near_list.get(near_cur_index).getNick() );
						chatIntent.putExtra("mId",near_list.get(near_cur_index).getId());						
					}
					context.startActivity(chatIntent);
				} catch (JSONException e) {
					//L.showShort(context, "网络异常,请重新操作");
					e.printStackTrace();
				}

    		}
    		@Override
    		public void onFailure(Throwable error) {
    			// TODO Auto-generated method stub
    			L.showShort(context, "网络异常,请重新操作");
    		}

    	});
	}
	public void initLoadHome(){
		
	}
}
	






